package com.zhiban.project.controller;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

import dinamica.Db;
import dinamica.Recordset;
import dinamica.audit.AuditableTransaction;

/**
 * 试卷自动组卷
 * 
 * @author lxp
 *
 */
public class ExamAutoAddController extends AuditableTransaction {

	public int service(Recordset inputParams) throws Throwable {
		String insert = getSQL(getResource("insert.sql"), inputParams);
		getDb().exec(insert);
		String getrecord = getSQL(getResource("getrecord.sql"), inputParams);
		Recordset recordset = getDb().get(getrecord);
		Integer tuid = null;
		if (recordset.next()) {
			tuid = recordset.getInteger("tuid");
		}
		HttpServletRequest request = getRequest();
		String question_num[] = request.getParameterValues("question_num");
		String question_score[] = request.getParameterValues("question_score");
		String areaIdStr=request.getParameter("areaId");
		Integer areaId=0;
		if (StringUtils.isNotBlank(areaIdStr)) {
			areaId=Integer.parseInt(areaIdStr);
		}
		Integer  airportId=0;
		Object airportIdObject=request.getSession().getAttribute("airportId");
		if (airportIdObject!=null && StringUtils.isNotBlank(airportIdObject.toString())) {
			airportId=Integer.parseInt(airportIdObject.toString());
		}
		callProc(getDb(), reverseArr(question_num), reverseArr(question_score),
				tuid,areaId,airportId);
		int rc = 0;
		
		String sqlAudit = getConfig().getConfigValue("//audit/recordset");//添加日志
		if (sqlAudit != null && !sqlAudit.equals(""))
		{
			Recordset rs = getDb().get(getSQL(getResource(sqlAudit), inputParams));
			publish(sqlAudit, rs);
		}
		return rc;
	}

	private String reverseArr(String question_score[]) {
		StringBuilder stringBuffer = new StringBuilder();
		if (question_score != null) {
			for (int i = question_score.length - 1; i >= 0; i--) {
				stringBuffer.append(question_score[i] + ",");
			}
			if (question_score.length > 0) {
				stringBuffer.delete(stringBuffer.length() - 1,
						stringBuffer.length());
			}
		}
		return stringBuffer.toString();
	}

	/**
	 * 生成题目
	 * 
	 * @param db
	 * @param str
	 *            题量数
	 * @param score
	 *            分数
	 * @param tuid
	 * @throws SQLException
	 */
	private void callProc(Db db, String str, String score, Integer tuid,Integer areaId,Integer airportId)
			throws SQLException {
		Connection connection = db.getConnection();
		CallableStatement stmt = connection
				.prepareCall("call grouppaper(?,?,?,?,?)");
		stmt.setString(1, str);
		stmt.setString(2, score);
		stmt.setInt(3, tuid);
		stmt.setInt(4, areaId);
		stmt.setInt(5, airportId);
		stmt.executeUpdate();
		if (!stmt.isClosed()) {
			stmt.close();
		}
	}

}
